#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
#define BUFFSIZE 1024

int
main(int argc, char *argv[])
{
    if (argc < 3)
    {
        fprintf(stderr,"Usage %s sourcefile destfile\n",argv[0]);
        exit(1);
    }
    
    int sfd,dfd;
    char buf[BUFFSIZE];
    size_t len;
    size_t wlen;
    int pos = 0;
    sfd = open(argv[1],O_RDONLY);
    if (sfd < 0)
    {
        perror("open()");
        exit(1);
    }
    
    dfd = open(argv[2],O_WRONLY|O_CREAT|O_TRUNC,00644);
    if (dfd < 0)
    {
        close(sfd);
        perror("open()");
        exit(1);
    }
    

    while (1)
    {
        len = read(sfd,buf,BUFFSIZE);
        if (len < 0)
        {
            perror("read()");
            break;
        }
        if (len == 0)
        {
            break;
        }
        
        while (len > 0)
        {
            wlen = write(dfd,buf+pos,len);
            if (wlen < 0)
            {
                perror("write()");
                // close(sfd);
                // close(dfd);
                exit(1);
            }
            pos += wlen;
            len -= wlen;
        }
    }
    
    close(sfd);
    close(dfd);
    exit(0);
}
